package com.hqyj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.controller.CaptchaController;
import com.hqyj.dao.UserMapper;
import com.hqyj.pojo.User;
import com.hqyj.service.UserService;
import com.hqyj.utile.GetTime;
import com.hqyj.utile.MdFive;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper mapper;

    public HashMap<String, Object> regist(User user,HttpServletRequest request) {
        HashMap<String, Object> map=new HashMap<String, Object>();
        HttpSession session=request.getSession();
        String code = session.getAttribute("code")+"";
        if (code.equals(user.getCode())) {
            //查询用户名是否存在
            int i = mapper.selectByName(user.getUserName());
            //查询邮箱是否存在
            if (i > 0) {
                map.put("info", "用户已存在");
            } else {
                //加密
                String pwd = MdFive.encrypt(user.getUserPassword(), user.getUserName());
                user.setUserPassword(pwd);
                System.out.println("当前的时间为："+GetTime.getNowTime());
                user.setLoginTime(GetTime.getNowTime());
                int n = mapper.insertLoginUser(user);
                if (n!=0){
                    int userId = mapper.selectUserIdByName(user.getUserName());
                    System.out.println("id为："+userId);
                    mapper.inserIntoUserRoleByLoginUser(userId);
                }

                if (n > 0) {
                    map.put("info", "注册成功");
                } else {
                    map.put("info", "注册失败");
                }
            }
        } else {
            map.put("info","验证码错误");
        }
        return map;
    }

    public HashMap<String, Object> selectList(User user) {
        return null;
    }

    public HashMap<String, Object> update(User user) {
        return null;
    }

    public HashMap<String, Object> delete(Integer aId) {
        return null;
    }

    public User selectById(Integer sysId) {
        return null;
    }

    //登录校验
    public HashMap<String, Object> login(User user, HttpServletRequest request) {
        HashMap<String, Object> map=new HashMap<String, Object>();
        //校验验证码
        // 1、获取session中验证码
        String code=(String)SecurityUtils.getSubject().getSession().getAttribute(CaptchaController.KEY_CAPTCHA);
        map.put("code",code);
        if (null == code || !code.equalsIgnoreCase(user.getCode())) {
            map.put("info", "验证码错误");
        } else {
            //1、获取令牌：拿到用户名，密码
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(),user.getUserPassword());
            //2、获取shiro用户对象
            Subject subject= SecurityUtils.getSubject();
            //3、登录
            try {
                subject.login(token);
                HttpSession session = request.getSession();
                int userId =  mapper.selectUserIdByName(user.getUserName());
                int userNumber = mapper.selectNumber();
                System.out.println("此时的userId为：========"+userId);
                session.setAttribute("userName",user.getUserName());
                session.setAttribute("userId",userId);
                session.setAttribute("number",userNumber);
                map.put("info","登陆成功");
            } catch (UnknownAccountException u) {
                u.printStackTrace();
                map.put("info", "用户名不存在");
            } catch (IncorrectCredentialsException io) {
                io.printStackTrace();
                map.put("info","密码校验失败");
            }
        }

        return map;
    }


    public HashMap<String, Object> bitDel(String arrId) {
        return null;
    }

    public HashMap<String, Object> selectListAll(User user,HttpServletRequest request) {
        HashMap<String,Object> map = new HashMap<String, Object>();
        //1设置分页查询的页码。每页显示的行数,PAGE：第一页      row：第一页里面有2条数据
        PageHelper.startPage(user.getPage(),user.getRow());
        System.out.println("你好烦啊啊啊啊啊啊："+PageHelper.startPage(user.getPage(),user.getRow()).getPages());
        //2查询
        user.setUserName("%"+user.getUserName()+"%");
        List<User> list = GetTime.transferToTime(mapper.selectListAll(user)) ;
        //3.创建分页对象，里面穿插了getPage和row
        PageInfo<User> pageInfo = new PageInfo<User>(list);
        //4.获取当前页的集合，就只
        System.out.println("你到底有好多页哦？"+pageInfo.getPages());
        map.put("list",pageInfo.getList());
        //5.总条数
        Long total = pageInfo.getTotal();
        //6.总页数
        int totalPage = pageInfo.getPages();
        map.put("total",total);
        map.put("totalPage",totalPage);
        System.out.println("返回来的数据为：" + list);
        return map;
    }
}
